package com.android.equipment.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.equipment.R;
import com.android.equipment.adapter.WorkAdapter;
import com.android.equipment.base.BaseFragment;
import com.android.equipment.dao.Work;
import com.android.equipment.dao.operate.DaoWork;
import com.android.equipment.databinding.FragmentHomeBinding;
import com.android.equipment.ui.MainActivity;
import com.android.equipment.ui.dialog.CreateWorkDialog;
import com.android.equipment.ui.work.WorkDetailActivity;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.utils.DateUtils;
import com.lxj.xpopup.XPopup;

import java.util.List;
import java.util.Objects;

public class HomeFragment extends BaseFragment {
    FragmentHomeBinding binding;
    private WorkAdapter workAdapter;

    @Override
    protected View setLayoutContent(LayoutInflater inflater, ViewGroup container) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        initRecycler();
    }

    @Override
    protected void initData() {

    }

    private void refreshData() {
        List<Work> workList = DaoWork.getInstance().getAll();
        workAdapter.setList(workList);
    }

    private void initRecycler() {
        workAdapter = new WorkAdapter(R.layout.item_work);
        binding.rvWork.setAdapter(workAdapter);
        workAdapter.setOnItemClickListener((adapter, view, position) -> {
            Work item = workAdapter.getItem(position);
            Intent intent = new Intent(getContext(), WorkDetailActivity.class);
            intent.putExtra("workId", item.getId());
            ((MainActivity) requireActivity()).mSwipeBackHelper.forward(intent);
        });

        // TODO: 2024/6/4 临时添加删除功能  方便测试 
//        workAdapter.setOnItemLongClickListener((adapter, view, position) -> {
//            DaoWork.getInstance().delWork(workAdapter.getItem(position));
//            refreshData();
//            return false;
//        });
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        binding.llAdd.setOnClickListener(v -> {
            new XPopup.Builder(getContext())
                    .asCustom(new CreateWorkDialog(requireContext(), name -> {
                        Work work = new Work();
                        work.setName(name);
                        work.setAddTime(DateUtils.getYearDataFormat(System.currentTimeMillis()));
                        DaoWork.getInstance().addWork(work);
                        refreshData();
                    }))
                    .show();
        });


    }


    @Override
    public void onResume() {
        super.onResume();
        refreshData();
        ImmersionBar.with(this).init();
    }

}
